﻿using System;
using System.Globalization;
using System.Web.UI.WebControls;
using ContractManagementSystem.BusinessLogicLayer;
using ContractManagementSystem.EntityObjects;

namespace ContractManagementSystem.Presentation.TimesheetManagement
{
    public partial class ListTimesheet : System.Web.UI.Page
    {
        private TimesheetDetailEntity _timesheetEntity;
        private int _roleId;
        private string _userName;

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckUserPermission();
            if (Session["RoleId"] != null)
            {
                _roleId = int.Parse(Session["RoleId"].ToString(), CultureInfo.InvariantCulture);
                              
                if (!IsPostBack)
                {
                    BindData();
                    BindContractNumber();
                }
            }
        }

        //Bind data listview timesheet
        private void BindData()
        {
            _roleId = int.Parse(Session["RoleId"].ToString(), CultureInfo.InvariantCulture);
            _userName = Session["UserName"].ToString();

            if (_roleId == 1 || _roleId == 3)
            {
                listTimesheet.DataSource = TimesheetLogic.SelectDataTimesheet();
            }
            else if (_roleId == 2)
            {
                listTimesheet.DataSource = TimesheetLogic.SelectDataTimesheetByUserName(_userName);
            }
            else if(_roleId==4)
            {
                listTimesheet.DataSource = TimesheetLogic.SelectDataTimesheetByConsultant(_userName);
            }
            listTimesheet.DataBind();
        }
        //Bind data dropDownList Contract Number
        protected void BindContractNumber()
        {
            _roleId = int.Parse(Session["RoleId"].ToString(), CultureInfo.InvariantCulture);
            _userName = Session["UserName"].ToString();
            if (_roleId == 1 || _roleId == 3)
            {
                var result = ContractLogic.ListActiveContracts();
                dropContract.DataSource = result;
            }
            else if(_roleId==4)
            {
                var result = ContractLogic.ListActiveContractsByConsultant(_userName);
                dropContract.DataSource = result;
            }
            else if(_roleId==2)
            {
                var result = ContractLogic.ListActiveContractsByContractor(_userName);
                dropContract.DataSource = result;
            }

            dropContract.DataTextField = "ContractNumber";
            dropContract.DataValueField = "ContractNumber";
            dropContract.DataBind();
            dropContract.Items.Insert(0,new ListItem("All","All"));
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ButtonSearchClick(null,null);
            listTimesheet.DataBind();
        }
        /**/
        protected void ListTimesheetItemDeleting(object sender, ListViewDeleteEventArgs e)
        {}

        protected void ListTimesheetItemCommand(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                var id = int.Parse(e.CommandArgument.ToString(), CultureInfo.InvariantCulture);
                _timesheetEntity = new TimesheetDetailEntity
                                     {
                                         TimesheetDetailId = id
                                     };
                var delete = TimesheetLogic.DeleteTimesheet(_timesheetEntity);
                if (delete != null)
                {
                    BindData();
                }
                else
                {
                    // Save event of logging out
                    var userEventEntity = new EventEntity
                    {
                        UserName = CommonLogic.ConvertToString(Session["UserName"]),
                        OnDate = DateTime.Now,
                        EventType = (int)EventTypeList.SystemEvent,
                        Description = "User delete timesheet failed"
                    };

                    EventTracer.SaveEvents(userEventEntity);
                }
            }
        }
        /// <summary>
        /// Search timesheet by line manager
        /// </summary>
        protected void FilterTimesheet()
        {
            var contractDrop =  dropContract.SelectedValue;
            var statusDrop =  dropStatus.SelectedValue;
            var fromDateText =  textFromDate.Text;
            var toDateText = textToDate.Text;
            var sortDrop =  dropSort.SelectedValue;

            var result = TimesheetLogic.SearchTimesheet(contractDrop, statusDrop, fromDateText, toDateText, sortDrop);
            if (result == null)
            {
                return;
            }

            listTimesheet.DataSource = result;
            listTimesheet.DataBind();
        }
        /// <summary>
        /// Search timesheet by role contractor
        /// </summary>
        protected void FilterTimesheetByContractor()
        {
            var contractDrop =  dropContract.SelectedValue;
            var statusDrop =  dropStatus.SelectedValue;
            var fromDateText = textFromDate.Text;
            var toDateText =  textToDate.Text;
            var sortDrop =  dropSort.SelectedValue;

            var userName = Session["UserName"].ToString();

            var result = TimesheetLogic.SearchTimesheetByUserName(contractDrop, statusDrop, fromDateText, toDateText, sortDrop, userName);
            if (result == null)
            {
                return;
            }

            listTimesheet.DataSource = result;
            listTimesheet.DataBind();
        }
        /// <summary>
        /// Search timesheet of contractor by role consultant
        /// </summary>
        protected void FilterTimesheetByConsultant()
        {
            var contractDrop = dropContract.SelectedValue;
            var statusDrop =  dropStatus.SelectedValue;
            var fromDateText = textFromDate.Text;
            var toDateText =  textToDate.Text;
            var sortDrop =  dropSort.SelectedValue;

            var userName = Session["UserName"].ToString();

            var result = TimesheetLogic.SearchTimesheetByConsultant(contractDrop, statusDrop, fromDateText, toDateText, sortDrop, userName);
            if (result == null)
            {
                return;
            }

            listTimesheet.DataSource = result;
            listTimesheet.DataBind();
        }

        protected void ButtonSearchClick(object sender, EventArgs e)
        {
            _roleId = int.Parse(Session["RoleId"].ToString(), CultureInfo.InvariantCulture);

            switch (_roleId)
            {
                case 3:
                case 1:
                    FilterTimesheet();
                    break;
                case 2:
                    FilterTimesheetByContractor();
                    break;
                case 4:
                    FilterTimesheetByConsultant();
                    break;
            }
        }

        // Check user's permissions
        private void CheckUserPermission()
        {
            var userName = CommonLogic.ConvertToString(Session["UserName"]);
            const int functionId = (int)FunctionList.ListTimesheet;

            var urlToCome = Page.Master.ResolveUrl("Presentation/AuthorizationError.aspx");

            AuthorizationChecker.IsValidAuthorization(userName, functionId, Response, urlToCome);
        }

    }
}
